<template>
  <div class="modal" v-if="dish" @click="handleBackgroundClick">
    <div class="modal-content" @click.stop>
      <span class="close-button" @click="close">&times;</span>

      <div class="content-container">
        <div class="left-panel">
          <img :src="getImageUrl(dish.image_url)" alt="Dish image" class="dish-image"/>

          <div class="dish-info">
            <h3>{{ dish.name }}</h3>
            <p class="dish-description">{{ dish.description }}</p>
          </div>

        </div>

        <div class="right-panel" >
          <h4>原料信息:</h4>
          <table class="ingredients-table" v-if="ingredients.length">
            <thead>
            <tr>
              <th>原料名称</th>
              <th>采购日期</th>
              <th>供应商</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="ingredient in ingredients" :key="ingredient.ingredient_id">
              <td>{{ ingredient.name }}</td>
              <td>{{ ingredient.purchase_date }}</td>
              <td>{{ ingredient.supplier }}</td>
            </tr>
            </tbody>
          </table>

          <div class="feedback-form">
            <h7>反馈口味:</h7>
            <textarea v-model="feedback" placeholder="请输入您对此菜品的反馈"></textarea>
            <button @click="submitFeedback">提交反馈</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getIngredientsByDishId } from '@/api/ingredients'; // 导入API函数
import { submitDishFeedback } from '@/api/dishes'; // 导入API函数
import { getAccessToken } from '@/utils/auth'; // Import the method to get the access token

import { baseURL } from '@/utils/request'; // 导入baseURL

export default {
  name: 'DishDetailCard',
  props: {
    dish: {
      type: Object,
      required: false
    }
  },
  data() {
    return {
      ingredients: [], // 存储食材信息的数组
      feedback: '',

    };
  },
  mounted() {
    console.log('DishDetailCard mounted. Initial dish:', this.dish);
    if (this.dish && this.dish.dish_id) {
      this.fetchIngredients();
    }
  },
  methods: {
    getImageUrl(path) {
      return `${baseURL}${path}`;
    },

    close() {
      this.$emit('close');
    },

    handleBackgroundClick() {
      this.$emit('close');
    },

    fetchIngredients() {
      console.log('Fetching ingredients for dish:', this.dish); // 打印当前的 dish 对象

      if (this.dish && this.dish.dish_id) {
        console.log('Fetching ingredients for dish ID:', this.dish.dish_id); // 打印 dish_id

        getIngredientsByDishId(this.dish.dish_id)
            .then(response => {
              console.log('Test respronse fetched:', response);

              if (response && response.data) {
                this.ingredients = response.data;
                console.log('Test INGREDIENTS fetched:', this.ingredients);

              } else {
                console.error('Invalid response structure:', response);
                this.ingredients = [];
              }
            })
            .catch(error => {
              console.error('Error fetching ingredients:', error);
              this.ingredients = [];
            });
      }
    },

    submitFeedback() {
      const token = this.getAccessToken();
      if (!token) {
        alert('请先登录');
        this.$router.push('/login'); // 使用 Vue Router 的 push 方法跳转
        return;
      }

      // console.log('Submitting feedback:', this.feedback);


      // 发送请求并处理响应
      submitDishFeedback(token, this.dish.dish_id, this.feedback)
          .then(response => {
            // 根据响应显示消息
            if (response && response.data) {
              // 假设后端返回的成功消息存储在response.data.message中
              this.feedback = '' ;

              alert(response.data.message || '反馈提交成功');
            } else {
              // 若没有明确的消息，则失败
              alert('反馈提交失败了');
            }
          })
          .catch(error => {
            // 处理错误情况
            if (error.response && error.response.data) {
              // 假设后端返回的错误消息存储在error.response.data.message中
              alert(error.response.data.message || '反馈提交失败');
            } else {
              // 若没有明确的错误消息，则显示默认错误消息
              alert('反馈提交失败');
            }
            console.error('反馈提交失败', error);
          });
      },
    getAccessToken() {
      // Retrieve the access token
      return getAccessToken();
    }
  }
};

</script>




<style scoped>
.modal {
  z-index: 1000;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
}



.modal-content {
  background: white;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  //margin-top: 5vw;
  width: 90vw; /* 或具体的固定宽度 */
  max-width: 900px; /* 最大宽度 */
  height: 70vh; /* 设定一个固定高度或最大高度 */
  max-height: 95vh; /* 最大高度 */
  overflow-y: auto; /* 垂直方向上溢出时显示滚动条 */
  box-shadow: 0 4px 10px rgba(0,0,0,0.2);
}


.close-button {
  float: right;
  font-size: 1.5em;
  cursor: pointer;
}

.ingredients-table {
  width: 100%; /* 设置表格宽度 */
  border-collapse: collapse; /* 去除单元格之间的间隔 */
}

.ingredients-table th,
.ingredients-table td {
  border: 1px solid #ddd; /* 单元格边框 */
  padding: 8px; /* 单元格内边距 */
  text-align: left; /* 文本对齐 */
}

.ingredients-table th {
  background-color: #f4f4f4; /* 表头背景颜色 */
  font-weight: bold; /* 字体加粗 */
}

.ingredients-table tr:nth-child(even) {
  background-color: #f9f9f9; /* 条纹效果 */
}


.content-container {
  display: flex;
  justify-content: space-between;
  align-items: center; /* 新增：垂直居中对齐 */
  height: 100%; /* 确保容器高度填满可用空间 */
}

.left-panel, .right-panel {
  flex: 1; /* 两边各占一半宽度 */
  margin: 0 5px; /* 添加一些间距 */
  display: flex; /* 新增：使用Flex布局 */
  flex-direction: column; /* 新增：垂直排列子元素 */
  justify-content: center; /* 新增：垂直居中对齐 */
  align-items: center;
}

.dish-image {
  max-width: 90%; /* 图片宽度调整为100% */
  height: 30vh; /* 高度自适应 */
  object-fit: cover; /* 保持图片的比例 */
  margin-bottom: 1px; /* 新增：图片与下方文本间距 */
}

.feedback-form {
  width: 35vh; /* 宽度设置为100% */
  height: 15vh; /* 设置一个固定高度 */
  margin-bottom: 10px; /* 与提交按钮的间距 */
}
.feedback-form textarea {
  width: 100%; /* 宽度设置为100% */
  height: 100%; /* 设置一个固定高度 */
  margin-bottom: 10px; /* 与提交按钮的间距 */
}

.feedback-form button {
  //margin-top: auto;
  //margin-bottom: 40%;
  padding: 10px 20px; /* Add more padding for a larger button */
  background-color: #93bdd8; /* A green background for visibility */
  color: white; /* White text for contrast */
  border: none; /* Remove default border */
  border-radius: 5px; /* Slightly rounded corners */
  font-size: 1em; /* Larger font size */
  cursor: pointer; /* Cursor changes to pointer to indicate it's clickable */
  transition: background-color 0.3s, transform 0.1s; /* Smooth transition for hover effects */
  width: 50%; /* Set the width to 50% of the parent element */
  margin-left: auto; /* Center the button horizontally */
  margin-right: auto; /* Center the button horizontally */

}

.feedback-form button:hover, .feedback-form button:focus {
  background-color: #A4D3F1; /* Darker shade of green on hover/focus */
  transform: translateY(-2px); /* Slight raise effect on hover/focus */
  outline: none; /* Remove outline on focus for cleaner look */
}

h7 {
  font-weight: bold; /* 加粗文本 */
}

</style>
